package com.book.lizhi.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Scroller;

public class CustomView extends View {
	private Scroller mScroller;

	public CustomView(Context context) {
		super(context);
		initView(context);
	}

	public CustomView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(context);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		setMeasuredDimension(measureWidth(widthMeasureSpec), measuredHeight(heightMeasureSpec));
	}

	private int measuredHeight(int heightMeasureSpec) {
		int height;
		int specMode = MeasureSpec.getMode(heightMeasureSpec);
		int specSize = MeasureSpec.getSize(heightMeasureSpec);
		if (specMode == MeasureSpec.EXACTLY) {
			height = specSize;
		} else {
			height = 2;
		}
		return height;
	}

	private int measureWidth(int widthMeasureSpec) {
		int width;
		int specMode = MeasureSpec.getMode(widthMeasureSpec);
		int specSize = MeasureSpec.getSize(widthMeasureSpec);
		if (specMode == MeasureSpec.EXACTLY) {
			width = specSize;
		} else {
			width = 100;
		}
		return width;
	}

	private void initView(Context context) {
		mScroller = new Scroller(context);
	}

	public void scrollerTo(int x, int y, int oldx, int oldy) {
		mScroller.startScroll(x, y, oldx, oldy, 10);
	}

	@Override
	public void computeScroll() {
		if (mScroller.computeScrollOffset()) {
			scrollTo(mScroller.getCurrX(), 0);
			postInvalidate();
		}
	}
}
